package com.hxz.djbxkj.HxzExecutor.Model;


import com.hxz.djbxkj.HxzExecutor.zy.RunType;

public class TaskMode {
    private String name;
    private int state= RunType.WQD;
    private StringBuffer errerMsg;//错误信息收集器

    private long begin=0l;
    private long end=0l;

    private JobMode[] jm;

    private boolean synchroniz=true;//默认与主线程保持同步

    /**
     * 构造器
     * @param name 主任务名称
     * @param jm 异步任务数组
     */
    public TaskMode(String name,JobMode[] jm){
        this.name=name;
        this.jm=jm;
    }

    public JobMode[] getJobModeS(){
        return jm;
    }

    public TaskMode setJobMode(int i, JobMode j){
        jm[i]=j;
        return this;
    }

    public int getState() {
        return state;
    }

    public TaskMode setState(){
        boolean flag=true;
        for(JobMode j:jm){
            if(j.getState()==RunType.WQD||j.getState()==RunType.ZXZ){
                flag=false;
            }
        }
        if(flag){
            this.state=RunType.ZXW;
        }
        return this;
    }

    public String getMeg(){
        errerMsg=new StringBuffer();
        for(JobMode j:jm){
            if(!j.getMeg().trim().equals("")){
                errerMsg.append("["+this.name+"]错误信息===》["+j.getMeg()+"]\r\n");
            }
        }
        return errerMsg.toString();
    }

    public TaskMode setBegin() {
        this.begin = System.currentTimeMillis();
        return this;
    }

    public TaskMode setEnd() {
        this.end = System.currentTimeMillis();
        return this;
    }

    public long getHs(){
        return this.end-this.begin;
    }

    public String getName() {
        return name;
    }

    public boolean getSynchroniz() {
        return synchroniz;
    }

    /**
     * 该方法可以剥夺线程进入阻塞状态，
     * 因此必须通过endTask()函数才可以结束Task；
     * @param synchroniz
     */
    public void setSynchroniz(boolean synchroniz) {
        this.synchroniz = synchroniz;
    }

    public final static TaskMode endTask(TaskMode tm){
        while (tm.getState()== RunType.WQD ||tm.getState()== RunType.ZXZ){
            tm.setState();
            if(tm.getState()== RunType.WQD ||tm.getState()== RunType.ZXZ){
                Thread.yield();
            }
        }
        tm.setEnd();
        return tm;
    }
}
